#include "MWSystem.h"

using namespace Myway;

IMP_SLN(System);

System::System()
: mLogSystem(NULL)
, mLastFrameTime(0)
, mFrameTime(0)
, mLastFPSCalcTime(0)
, mFPS(0)
{
	msInstance = this;
}

System::~System()
{
    msInstance = NULL;
}

void System::Init(const char * resource, const char * log)
{
    Memory::Init();
    Math::Init();

    mLogSystem = new LogSystem();
    mResourceManager = new ResourceManager();

    LogSystem::Instance()->Init(log);

    ResourceManager::Instance()->AddArchiveFactory(new FileSystemFactory());

    ParseConfig(resource);

	mTimer.Start();
}

void System::Shutdown()
{
    safe_delete(mResourceManager);
    safe_delete(mLogSystem);

	Math::Shutdown();
    Memory::Shutdown();
}

void System::ParseConfig(const char * sFileName)
{
    xml_doc doc;

    char * data = XmlHelper::LoadXmlFromFile(doc, sFileName);

    xml_node * node = doc.first_node()->first_node("resources");

    while (node)
    {
        const char * type = node->first_attribute("type")->value();
        const char * path = node->first_attribute("path")->value();
        ResourceManager::Instance()->AddArchive(path, type);

        node = node->next_sibling("resources");
    }

    ResourceManager::Instance()->Init();

    safe_free(data);
}

void System::Run()
{
    float time = GetTime();

    mFrameTime = time - mLastFrameTime;
    mLastFrameTime = time;

    if (time - mLastFPSCalcTime > 1.0f)
    {
        mFPS = mFrameTime ? 1.0f / mFrameTime : 0;
        mLastFPSCalcTime = time;
    }
}

float System::GetFrameTime()
{
    return mFrameTime;
}

float System::GetFPS()
{
    return mFPS;
}

float System::GetTime()
{
    return mTimer.ElapsedTime();
}

